package st.business.tepth.business.visitor;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import io.reactivex.disposables.Disposable;
import st.business.tepth.R;
import st.business.tepth.base.OnItemChooseListener;
import st.business.tepth.business.bean.FactoryPersonBean;
import st.business.tepth.business.bean.PersonBean;
import st.business.tepth.config.Url;
import st.shadow.library.core.net.callback.IError;
import st.shadow.library.core.net.callback.ISuccess;
import st.shadow.library.core.net.data.ObjConverter;
import st.shadow.library.core.net.rx.RxRestClient;
import st.shadow.library.core.storage.ShadowPreference;
import st.shadow.library.core.util.utilcode.util.DeviceUtils;
import st.shadow.library.ui.indicator.magicindicator.MagicIndicator;
import st.shadow.library.ui.indicator.magicindicator.ViewPagerHelper;
import st.shadow.library.ui.indicator.magicindicator.buildins.UIUtil;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.CommonNavigator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.indicators.WrapPagerFillIndicator;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;
import st.shadow.library.ui.indicator.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView;
import st.shadow.library.ui.recycler.MultipleItemEntity;

/**
 * @author zhangyu
 * @date 2019/2/18
 */
public class DialogLogin extends Dialog {
    private Disposable mDisposable;
    private ViewPager viewPager;
    private OnItemChooseListener<String> mListener;

    public DialogLogin(final Context context,
                       final OnItemChooseListener<String> listener) {
        super(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mListener = listener;
        View view = LayoutInflater.from(context).
                inflate(R.layout.dialog_login, null);
        final ConstraintLayout container = view.findViewById(R.id.layout_container);
        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        viewPager = view.findViewById(R.id.view_pager_group);
        final MagicIndicator indicator = view.findViewById(R.id.indicator);
        addTopView(R.layout.view_loading, container);
        mDisposable = RxRestClient.builder().url(Url.GetFactoryPersons)
                .params("workbenchNo", DeviceUtils.getAndroidID())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        List<FactoryPersonBean> groups =
                                new ObjConverter<List<FactoryPersonBean>>().convert(response
                                        , new TypeReference<List<FactoryPersonBean>>() {
                                        });
                        removeTopView(container);
                        if (groups != null) {
                            String groupName = ShadowPreference.getCustomAppProfile("loginGroup");
                            int position = 0;
                            final List<RecyclerView> list = new ArrayList<>();
                            for (int i = 0, size = groups.size(); i < size; i++) {
                                FactoryPersonBean group = groups.get(i);
                                if (groupName.equals(group.getGroupName())) {
                                    position = i;
                                }
                                RecyclerView recyclerView = new RecyclerView(getContext());
                                recyclerView.setLayoutManager(new GridLayoutManager(context,
                                        5));
                                final PersonAdapter personAdapter = new PersonAdapter(convertData(group));
                                personAdapter.setSpanSizeLookup(new BaseQuickAdapter.SpanSizeLookup() {
                                    @Override
                                    public int getSpanSize(GridLayoutManager gridLayoutManager, int position) {
                                        MultiItemEntity entity = personAdapter.getItem(position);
                                        if (entity != null) {
                                            return entity.getItemType() ==
                                                    PersonAdapter.TYPE_1 ? 5 : 1;
                                        } else {
                                            return 5;
                                        }
                                    }
                                });
                                recyclerView.setAdapter(personAdapter);
                                list.add(recyclerView);
                            }
                            if (position != 0) {
                                Collections.swap(groups, 0, position);
                                Collections.swap(list, 0, position);
                            }
                            viewPager.setAdapter(new PagerAdapter() {

                                @Override
                                public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                                    container.removeView((View) object);
                                }

                                @NonNull
                                @Override
                                public Object instantiateItem(@NonNull ViewGroup container, int position) {
                                    container.addView(list.get(position), ViewGroup.LayoutParams.MATCH_PARENT,
                                            ViewGroup.LayoutParams.MATCH_PARENT);
                                    return list.get(position);
                                }

                                @Override
                                public int getCount() {
                                    return list.size();
                                }

                                @Override
                                public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
                                    return view == o;
                                }
                            });
                            CommonNavigator commonNavigator = new CommonNavigator(getContext());
                            commonNavigator.setLeftPadding(0);
                            commonNavigator.setRightPadding(0);
                            commonNavigator.setAdapter(new GroupAdapter(groups));

                            indicator.setNavigator(commonNavigator);
                            ViewPagerHelper.bind(indicator, viewPager);
                        } else {
                            addTopView(R.layout.view_search_empty, container);
                        }

                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        removeTopView(container);
                        addTopView(R.layout.view_search_empty, container);
                    }
                })
                .build().post();
        setContentView(view);
    }

    @Override
    public void dismiss() {
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        super.dismiss();
    }

    private class GroupAdapter extends CommonNavigatorAdapter {
        private List<FactoryPersonBean> mList;

        public GroupAdapter(List<FactoryPersonBean> list) {
            mList = list;
        }

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public IPagerTitleView getTitleView(Context context, final int index) {
            FactoryPersonBean repairTaskBean = mList.get(index);
            final BadgePagerTitleView badgePagerTitleView = new BadgePagerTitleView(context);
            SimplePagerTitleView simplePagerTitleView =
                    new ColorTransitionPagerTitleView(context);
            simplePagerTitleView.setText(repairTaskBean.getGroupName());
            simplePagerTitleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
            simplePagerTitleView.setGravity(Gravity.CENTER);
            simplePagerTitleView.setBackground(context.getResources()
                    .getDrawable(R.drawable.shape_solid_trans_with_yellow_stroke));
            simplePagerTitleView.setNormalColor(Color.parseColor("#333333"));
            simplePagerTitleView.setSelectedColor(Color.parseColor("#333333"));
            simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    viewPager.setCurrentItem(index);
                    badgePagerTitleView.setBadgeView(null); // cancel badge when click tab
                }
            });
            badgePagerTitleView.setInnerPagerTitleView(simplePagerTitleView);
            return badgePagerTitleView;
        }

        @Override
        public IPagerIndicator getIndicator(Context context) {
            WrapPagerFillIndicator indicator = new WrapPagerFillIndicator(context);
            indicator.setRoundRadius(0);
            indicator.setHorizontalPadding(UIUtil.dip2px(context, 20));
            indicator.setFillColor(Color.parseColor("#f1b647"));
            return indicator;
        }
    }

    private class PersonAdapter extends BaseMultiItemQuickAdapter<MultipleItemEntity, BaseViewHolder> {

        public static final int TYPE_1 = 1;
        public static final int TYPE_2 = 2;

        /**
         * Same as QuickAdapter#QuickAdapter(Context,int) but with
         * some initialization data.
         *
         * @param data A new list is created out of this one to avoid mutable list
         */
        public PersonAdapter(List<MultipleItemEntity> data) {
            super(data);
            addItemType(TYPE_1, R.layout.item_login_type_1);
            addItemType(TYPE_2, R.layout.item_login_type_2);
        }

        @Override
        protected void convert(BaseViewHolder helper, final MultipleItemEntity item) {
            switch (item.getItemType()) {
                case TYPE_1:
                    helper.setText(R.id.tv_type, (CharSequence) item.getField("name"));
                    break;
                case TYPE_2:
                    helper.setText(R.id.tv_person, (CharSequence) item.getField("name"));
                    helper.getView(R.id.tv_person).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.onChoose((String) item.getField("code"));
                            }
                            ShadowPreference.addCustomAppProfile("loginGroup",
                                    (String) item.getField("groupName"));
                            dismiss();
                        }
                    });
                    break;
            }
        }
    }

    private List<MultipleItemEntity> convertData(FactoryPersonBean factoryPersonBean) {
        List<MultipleItemEntity> entityList = new ArrayList<>();
        List<FactoryPersonBean.RolesBean> rolesBeans = factoryPersonBean.getRoles();
        if (rolesBeans != null) {
            for (FactoryPersonBean.RolesBean rolesBean : rolesBeans) {
                entityList.add(MultipleItemEntity.builder()
                        .setItemType(PersonAdapter.TYPE_1)
                        .setField("name", rolesBean.getName())
                        .build());
                List<PersonBean> personBeans = rolesBean.getMember();
                if (personBeans != null) {
                    for (PersonBean personBean : personBeans) {
                        entityList.add(MultipleItemEntity.builder()
                                .setItemType(PersonAdapter.TYPE_2)
                                .setField("name", personBean.getUser_name() + "\n"
                                        + personBean.getJob_no())
                                .setField("code", personBean.getJob_no())
                                .setField("groupName", factoryPersonBean.getGroupName())
                                .build());
                    }
                }
            }
        }
        return entityList;
    }


    private void addTopView(int resourceId, ViewGroup group) {
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
        );
        group.addView(LayoutInflater.from(getContext()).inflate(resourceId, null)
                , group.getChildCount(), layoutParams);
    }

    private void removeTopView(ViewGroup group) {
        group.removeViewAt(group.getChildCount() - 1);
    }
}
